import { IRootReducerState } from '@/store/root-reducer';
import { Modal } from '@douyinfe/semi-ui';
import React, { useEffect, useMemo, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { useParams } from 'react-router-dom';
import ApplicationDetail from './detail';
import ApplicationEdit from './edit';
import * as actions from '../../../../redux/application/application-actions';
import { usePageContext } from '../context';
import { FormApi } from '@douyinfe/semi-ui/lib/es/form';

const ApplicationEntityDialog = ({ open, onClose, editable = true }: any) => {
  const dispatch = useDispatch<any>();
  const { id } = useParams();
  const PageContext = usePageContext();
  const [formApi, setFormApi] = useState<FormApi<any>>();
  const PageAction = useMemo(() => {
    return {
      queryParams: PageContext.queryParams,
    };
  }, [PageContext]);
  const { entities, actionsLoading } = useSelector<IRootReducerState, any>(
    (state) => ({
      actionsLoading: state.application.actionsLoading,
      entities: state.application.entities,
    }),
    shallowEqual
  );

  const [title, setTitle] = useState('');
  // Title couting
  useEffect(() => {
    let _title = id ? '' : '新建应用';
    if (id) {
      _title = `编辑应用`;
    }

    setTitle(_title);
    // eslint-disable-next-line
  }, [id, actionsLoading]);

  const entityForEdit = React.useMemo(() => {
    return id
      ? entities.filter((rule: any) => rule.id.toString() === id.toString())[0]
      : null;
  }, [entities, id]);
  // server request for saving entity
  const persistEntity = (entity: any) => {
    if (!id) {
      // @ts-ignore
      dispatch(actions.createItem(entity)).then(() => {
        onClose();
        dispatch(actions.fetchItems(PageAction.queryParams)).then(
          (res: any) => {
            console.log(res);
          }
        );
      });
    } else {
      // @ts-ignore
      dispatch(actions.updateItem(entity)).then(() => {
        onClose();
        dispatch(actions.fetchItems(PageAction.queryParams)).then(
          (res: any) => {
            console.log(res);
          }
        );
      });
    }
  };

  return (
    <Modal
      title={title}
      size='large'
      visible={open}
      // onOk={handleOk}
      onCancel={onClose}
      footer={null}
    >
      {editable ? (
        <>
          <ApplicationEdit
            formApiRef={setFormApi}
            persistEntity={persistEntity}
            entity={entityForEdit}
          />
        </>
      ) : (
        <ApplicationDetail entity={{}} />
      )}
    </Modal>
  );
};

export default ApplicationEntityDialog;
